package org.lojzes.minstruts.listener;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lojzes.minstruts.annotation.Action;
import org.lojzes.minstruts.annotation.RequestMapping;
import org.lojzes.minstruts.mappings.Mapping;
import org.lojzes.minstruts.scanner.ScanPackages;

public class ServletListener implements ServletContextListener {
	protected static Log log = LogFactory.getLog(ServletListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent contextEvent) {
		log.info("===>>用户注销！");
	}
    /**
     * 系统启动时获取action映射关系
     */
	@Override
	public void contextInitialized(ServletContextEvent contextEvent) {
		String annotationsPath = contextEvent.getServletContext().getInitParameter("annotations-path");
		Set<String> classPaths = ScanPackages.findPackageAnnotationClass(annotationsPath, Action.class);
		System.out.println(classPaths);
		HashMap<String, Mapping> actionMap = new HashMap<String, Mapping>();
		for (String path : classPaths) {
			try {
				Class<?> classz = Class.forName(path);
				Action actionNnotion = classz.getAnnotation(Action.class);
				Mapping mapping = new Mapping();
				HashMap<String, String> mappedMethod = new HashMap<String, String>();
				String actionName = actionNnotion.name();
				mapping.setActionClass(path);
				mapping.setActionName(actionName);
				System.out.println("actinName===>>" + actionName);
				Method[] methods = classz.getMethods();
				for (Method method : methods) {
					String parameter = "";
					if (method.isAnnotationPresent(RequestMapping.class)) {
						RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
						parameter = requestMapping.parameter();
						log.info("paramer===>>" + parameter);
						mappedMethod.put(parameter, method.getName());
						mapping.setMappedMethod(mappedMethod);
						actionMap.put(actionName+parameter, mapping);
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				log.info(e);
			}
		}
		contextEvent.getServletContext().setAttribute("actionMap", actionMap);
	}
}
